package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetOrderParam(param map[string]interface{}) (*models_main.Order, error) {
	fName := "GetOrderParam"
	o := &models_main.Order{}
	table := mysql.GetRTable(&models_main.Order{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetOrdersParam(param map[string]interface{}, order string, page, size int) ([]*models_main.Order, error) {
	fName := "GetOrdersParam"
	o := make([]*models_main.Order, 0)
	table := mysql.GetRTable(&models_main.Order{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetOrderCount(param map[string]interface{}) (int64, error) {
	fName := "GetOrderCount"
	var o int64
	table := mysql.GetRTable(&models_main.Order{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Count(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetOrderSum(param map[string]interface{}, column string) (float64, error) {
	fName := "GetOrderSum"
	o := &mysql.TotalFloat{}
	table := mysql.GetRTable(&models_main.Order{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Select(fmt.Sprintf("sum(%s) as s", column)).Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o.S, err
}

func InsertOrder(session *gorm.DB, order *models_main.Order) error {
	fName := "InsertOrder"
	if session == nil {
		session = global.GetX()
	}
	err := session.Create(order).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
func UpdateOrder(session *gorm.DB, columns []string, order *models_main.Order) error {
	fName := "UpdateOrder"
	if session == nil {
		session = global.GetX()
	}
	err := session.Where("").Select(columns).Updates(order).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
